package pod

import (
	"bufio"
	"context"
	"krm-backend/controllers"
	"krm-backend/utils/logs"
	"net/http"
	"time"

	"github.com/dotbalo/kubeutils/kubeutils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	v1 "k8s.io/api/core/v1"
)

// 1. container
// 2. follow
// 3. tailLines

func Logs(r *gin.Context) {
	logs.Debug(nil, "查看Pod日志")

	var info controllers.Info
	kubeconfig := controllers.NewInfo(r, &info, "获取成功")
	clientset, err := kubeutils.NewClientSet(kubeconfig, 0)
	if err != nil {
		logs.Debug(nil, "clientset创建失败")
		info.ReturnData.Message = "创建ClientSet失败:" + err.Error()
		info.ReturnData.Status = 400
		r.JSON(http.StatusOK, info.ReturnData)
		return
	}

	if info.TailLines == 0 {
		info.TailLines = 100
	}
	//创建logoptions
	getLogsOptions := v1.PodLogOptions{
		Container: info.Container,
		Follow:    true,
		TailLines: &info.TailLines,
	}
	//创建一个日志流
	//创建一个请求日志的request
	logRequest := clientset.CoreV1().Pods(info.Namespace).GetLogs(info.Name, &getLogsOptions)
	contextWithTimeout, cancel := context.WithTimeout(context.TODO(), time.Minute*5)
	defer cancel()
	//创建一个具有超时时间的日志流
	stream, err := logRequest.Stream(contextWithTimeout)
	if err != nil {
		info.ReturnData.Message = "创建日志流失败:" + err.Error()
		info.ReturnData.Status = 400
		r.JSON(http.StatusOK, info.ReturnData)
		return
	}
	//关闭日志流
	defer stream.Close()
	//升级为websocket协议
	ws := CreateWS(r)
	defer ws.Close()
	//创建一个bufio.Scanner
	reader := bufio.NewScanner(stream)
	for reader.Scan() {
		//拿到数据
		msg := reader.Text()
		logs.Debug(map[string]interface{}{"日志": msg}, "获取到日志")
		if err := ws.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
			//发送消息时失败的
			logs.Error(map[string]interface{}{"msg": err.Error()}, "写入日志数据失败")
			break
		}
	}
}
